﻿using NightskyMimic.Core;
using System;
using System.Collections.Generic;
using System.Linq;

namespace NightskyMimic.Domain
{
    public class Player
    {
        public string Name { get; private set; }

        public Zone Zone { get; set; }

        public Strategy Strategy { get; set; }

        public bool IsAlive
        {
            get { return Zone.Library.Count > 0 && Zone.Life > 0; }
        }

        public Player(string name, Zone zone, Strategy strategy) 
        {
            Name = name;
            Zone = zone;
            Strategy = strategy;
        }

        public void Begin() 
        {
            Zone.Library.Shuffle();

            for (int i = 0; i < 4; i++)
                Zone.DrawCard();
        }

        public void CastCreatures() 
        {
            int mana = Zone.Lands.Count;
            List<Creature> availableCreatures = Zone.Hand.Where(x => x.ManaCost <= mana && x is Creature).
                Select(x => x as Creature).OrderBy(x => x.CastCoefficient).Reverse().ToList();

            foreach (Creature c in availableCreatures) 
            {
                if (mana - c.ManaCost >= 0) 
                {
                    Zone.PutInPlay(c);
                    Console.WriteLine("cast " + c.ToString());
                    mana -= c.ManaCost;
                } 
            }
        }

        public void MainPhase() 
        {
            if (Zone.Hand.Any(x => x is Land)) 
            {
                Land land = Zone.Hand.First(x => x is Land) as Land;
                Zone.PutInPlay(land);
                Console.WriteLine("Cast " + land.Name);
            }

            CastCreatures();
            //Zone.UntapAllCards();
        }

        public void BegginingPhase() 
        {
            Zone.DrawCard();
            Zone.UntapAllCards();
        }

        public override string ToString()
        {
            return Name;
        }
    }
}